document.addEventListener('DOMContentLoaded', function() {
  // Initialize settings from localStorage
  loadSettings();
  
  // Event listeners
  document.getElementById('export-data-btn').addEventListener('click', exportData);
  document.getElementById('import-data-input').addEventListener('change', importData);
  document.getElementById('clear-data-btn').addEventListener('click', showClearDataConfirmation);
  document.getElementById('cloud-sync-toggle').addEventListener('change', toggleCloudSync);
  document.getElementById('sync-frequency').addEventListener('change', updateSyncFrequency);
  
  // JSONBin config
  document.getElementById('toggle-jsonbin-config').addEventListener('click', toggleJsonBinConfig);
  document.getElementById('jsonbin-api-key').addEventListener('input', saveJsonBinConfig);
  document.getElementById('jsonbin-bin-id').addEventListener('input', saveJsonBinConfig);
  document.getElementById('test-jsonbin-connection').addEventListener('click', testJsonBinConnection);
  
  // Sync history
  document.getElementById('toggle-sync-history').addEventListener('click', toggleSyncHistory);
  
  // Modal event listeners
  document.querySelectorAll('.modal-close, .modal-cancel').forEach(element => {
    element.addEventListener('click', closeModals);
  });
  
  // Close modal when clicking on the background
  document.getElementById('confirm-modal').addEventListener('click', function(event) {
    // Only close if the actual background was clicked (not the modal content)
    if (event.target === this) {
      closeModals();
    }
  });
  
  // Confirm modal action
  document.getElementById('confirm-action').addEventListener('click', handleConfirmAction);
  
  // Add click handler to notification to dismiss it
  document.getElementById('notification').addEventListener('click', function() {
    this.classList.remove('show');
  });
  
  // Initialize auto sync timer if enabled
  initializeAutoSync();
  
  // 新增手动同步按钮事件
  document.getElementById('manual-sync-btn').addEventListener('click', async function() {
    const manualSyncBtn = this;
    const originalContent = manualSyncBtn.innerHTML;
    manualSyncBtn.innerHTML = '<span>Syncing...</span>';
    manualSyncBtn.disabled = true;
    try {
      await syncWithJsonBin();
    } finally {
      manualSyncBtn.innerHTML = originalContent;
      manualSyncBtn.disabled = false;
    }
  });

  // Show Floating Timer toggle
  const showFloatingTimerToggle = document.getElementById('show-floating-timer-toggle');
  if (showFloatingTimerToggle) {
    // 初始化状态
    const showFloatingTimer = localStorage.getItem('showFloatingTimer');
    showFloatingTimerToggle.checked = showFloatingTimer === null ? true : showFloatingTimer === 'true';
    // 监听变更
    showFloatingTimerToggle.addEventListener('change', function() {
      localStorage.setItem('showFloatingTimer', this.checked);
    });
  }
});

// Current confirmation action
let currentConfirmAction = null;
// Store sync timer
let syncTimer = null;

// Load settings from localStorage
function loadSettings() {
  // Sync settings
  const cloudSyncEnabled = localStorage.getItem('cloudSyncEnabled') === 'true';
  document.getElementById('cloud-sync-toggle').checked = cloudSyncEnabled;
  
  // 只允许1min、1hour、3hour、9hour
  const validFrequencies = ['1min', '1hour', '3hour', '9hour'];
  let syncFrequency = localStorage.getItem('syncFrequency');
  if (!validFrequencies.includes(syncFrequency)) {
    syncFrequency = '1hour';
    localStorage.setItem('syncFrequency', syncFrequency);
  }
  document.getElementById('sync-frequency').value = syncFrequency;
  
  // JSONBin settings
  const jsonBinApiKey = localStorage.getItem('jsonBinApiKey') || '';
  const jsonBinBinId = localStorage.getItem('jsonBinBinId') || '';
  
  document.getElementById('jsonbin-api-key').value = jsonBinApiKey;
  document.getElementById('jsonbin-bin-id').value = jsonBinBinId;
}

// Export data
function exportData() {
  // 优先从 chrome.storage.local 读取
  if (window.chrome && chrome.storage && chrome.storage.local) {
    chrome.storage.local.get(['taskTrackerTasks'], function(result) {
      const tasksToExport = result.taskTrackerTasks || [];
      const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(tasksToExport, null, 2));
      const downloadAnchorNode = document.createElement('a');
      downloadAnchorNode.setAttribute("href", dataStr);
      downloadAnchorNode.setAttribute("download", "tasks_export_" + new Date().toISOString().split('T')[0] + ".json");
      document.body.appendChild(downloadAnchorNode);
      downloadAnchorNode.click();
      downloadAnchorNode.remove();
      showNotification('Task data exported successfully');
    });
    return;
  }
  // 兼容老逻辑
  const tasksToExport = JSON.parse(localStorage.getItem('taskTrackerTasks') || '[]');
  const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(tasksToExport, null, 2));
  const downloadAnchorNode = document.createElement('a');
  downloadAnchorNode.setAttribute("href", dataStr);
  downloadAnchorNode.setAttribute("download", "tasks_export_" + new Date().toISOString().split('T')[0] + ".json");
  document.body.appendChild(downloadAnchorNode);
  downloadAnchorNode.click();
  downloadAnchorNode.remove();
  showNotification('Task data exported successfully');
}

// Import data
function importData(e) {
  const file = e.target.files[0];
  if (!file) return;
  const reader = new FileReader();
  reader.onload = function(event) {
    try {
      const importedTasks = JSON.parse(event.target.result);
      if (!Array.isArray(importedTasks)) {
        throw new Error("Invalid data format");
      }
      const processedTasks = importedTasks.map(task => {
        const processedTask = {...task};
        if (!processedTask.createdAt) {
          processedTask.createdAt = new Date().toISOString();
        }
        if (typeof processedTask.time !== 'number') {
          processedTask.time = parseFloat(processedTask.time) || 0;
        }
        if (typeof processedTask.timeSpent !== 'number') {
          processedTask.timeSpent = parseFloat(processedTask.timeSpent) || 0;
        }
        if (!processedTask.notes) {
          processedTask.notes = "";
        }
        if (!processedTask.tags || !Array.isArray(processedTask.tags)) {
          processedTask.tags = [];
        }
        return processedTask;
      });
      // 保存到 localStorage
      localStorage.setItem('taskTrackerTasks', JSON.stringify(processedTasks));
      // 同步保存到 chrome.storage.local
      if (window.chrome && chrome.storage && chrome.storage.local) {
        chrome.storage.local.set({ taskTrackerTasks: processedTasks }, function() {
          showNotification(`Successfully imported ${processedTasks.length} tasks`);
        });
      } else {
      showNotification(`Successfully imported ${processedTasks.length} tasks`);
      }
    } catch (error) {
      showNotification(`Import failed: ${error.message}`, 'error');
    }
    e.target.value = '';
  };
  reader.readAsText(file);
}

// Show clear data confirmation
function showClearDataConfirmation() {
  document.getElementById('confirm-title').textContent = 'Clear All Data';
  document.getElementById('confirm-message').textContent = 'Are you sure you want to delete all task data? This action cannot be undone.';
  
  currentConfirmAction = 'clearData';
  document.getElementById('confirm-modal').classList.add('show');
}

// Handle confirm action
function handleConfirmAction() {
  switch (currentConfirmAction) {
    case 'clearData':
      clearAllData();
      break;
  }
  
  closeModals();
}

// Clear all data
function clearAllData() {
  // Only clear task data
  localStorage.removeItem('taskTrackerTasks');
  localStorage.removeItem('taskTrackerTimerStates');
  // 同步清除 chrome.storage.local
  if (window.chrome && chrome.storage && chrome.storage.local) {
    chrome.storage.local.remove(['taskTrackerTasks', 'taskTrackerTimerStates'], function() {
      showNotification('All task data has been cleared');
    });
  } else {
  showNotification('All task data has been cleared');
  }
}

// Toggle cloud sync
function toggleCloudSync(e) {
  const enabled = e.target.checked;
  localStorage.setItem('cloudSyncEnabled', enabled);
  
  // Update UI based on sync status
  document.getElementById('sync-frequency').disabled = !enabled;
  
  if (enabled) {
    // Check if JSONBin is configured
    const apiKey = localStorage.getItem('jsonBinApiKey');
    const binId = localStorage.getItem('jsonBinBinId');
    
    if (!apiKey || !binId) {
      // Show JSONBin config panel if not configured
      document.getElementById('jsonbin-config-panel').style.display = 'block';
      showNotification('Please configure JSONBin settings to enable sync', 'error');
    } else {
      // Perform initial sync
      syncWithJsonBin();
      // Initialize auto sync timer
      resetAutoSyncTimer();
    }
  } else {
    // Clear sync timer if sync is disabled
    if (syncTimer) {
      clearInterval(syncTimer);
      syncTimer = null;
    }
  }
  
  showNotification(enabled ? 'Cloud sync enabled' : 'Cloud sync disabled');
}

// Update sync frequency
function updateSyncFrequency(e) {
  const frequency = e.target.value;
  localStorage.setItem('syncFrequency', frequency);
  
  // Update auto sync timer
  resetAutoSyncTimer();
  
  showNotification('Sync frequency updated');
}

// Close all modals
function closeModals() {
  document.querySelectorAll('.modal').forEach(modal => {
    modal.classList.remove('show');
  });
}

// Show notification
function showNotification(message, type = 'success') {
  const notification = document.getElementById('notification');
  const messageElement = document.getElementById('notification-message');
  
  notification.className = 'notification ' + type + ' show';
  messageElement.textContent = message;
  
  // Auto-hide after 3 seconds
  setTimeout(() => {
    notification.classList.remove('show');
  }, 3000);
}

// Toggle JsonBin config panel
function toggleJsonBinConfig() {
  const configPanel = document.getElementById('jsonbin-config-panel');
  if (configPanel.style.display === 'none') {
    configPanel.style.display = 'block';
  } else {
    configPanel.style.display = 'none';
  }
}

// Save JsonBin config
function saveJsonBinConfig() {
  const apiKey = document.getElementById('jsonbin-api-key').value.trim();
  const binId = document.getElementById('jsonbin-bin-id').value.trim();
  
  localStorage.setItem('jsonBinApiKey', apiKey);
  localStorage.setItem('jsonBinBinId', binId);
}

// Test JsonBin connection
function testJsonBinConnection() {
  const apiKey = localStorage.getItem('jsonBinApiKey');
  const binId = localStorage.getItem('jsonBinBinId');
  
  if (!apiKey || !binId) {
    showNotification('Please enter API Key and Bin ID first', 'error');
    return;
  }
  
  // Show loading state
  const testButton = document.getElementById('test-jsonbin-connection');
  const originalContent = testButton.innerHTML;
  testButton.innerHTML = '<span>Testing...</span>';
  testButton.disabled = true;
  
  // Test connection to JSONBin
  fetch(`https://api.jsonbin.io/v3/b/${binId}`, {
    method: 'GET',
    headers: {
      'X-Master-Key': apiKey
    }
  })
  .then(response => {
    if (!response.ok) {
      throw new Error(`Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    showNotification('Connection successful! JSONBin is configured correctly.');
  })
  .catch(error => {
    showNotification(`Connection failed: ${error.message}`, 'error');
  })
  .finally(() => {
    // Restore button state
    testButton.innerHTML = originalContent;
    testButton.disabled = false;
  });
}

// Toggle sync history panel
function toggleSyncHistory() {
  const historyPanel = document.getElementById('sync-history-panel');
  if (historyPanel.style.display === 'none') {
    historyPanel.style.display = 'block';
    // 当展开面板时，加载同步历史记录
    loadSyncHistory();
  } else {
    historyPanel.style.display = 'none';
  }
}

// Load sync history
function loadSyncHistory() {
  // 从localStorage获取同步历史记录
  const syncHistory = JSON.parse(localStorage.getItem('syncHistory') || '[]');
  const historyList = document.querySelector('.sync-history-list');
  
  // 显示"无历史记录"或历史记录列表
  if (syncHistory.length === 0) {
    document.querySelector('.sync-history-empty').style.display = 'block';
    document.querySelectorAll('.sync-history-item').forEach(item => {
      item.style.display = 'none';
    });
  } else {
    document.querySelector('.sync-history-empty').style.display = 'none';
    
    // 获取所有历史记录项元素
    const historyItems = document.querySelectorAll('.sync-history-item');
    
    // 最多显示5条记录
    const recentHistory = syncHistory.slice(0, 5);
    
    // 更新每个历史记录项的内容
    recentHistory.forEach((record, index) => {
      if (index < historyItems.length) {
        const item = historyItems[index];
        item.style.display = 'flex';
        
        // 更新日期
        item.querySelector('.sync-history-date').textContent = formatDate(record.date);
        
        // 更新状态
        const statusEl = item.querySelector('.sync-history-status');
        statusEl.textContent = record.success ? 'Success' : 'Failed';
        statusEl.className = 'sync-history-status ' + (record.success ? 'success' : 'error');
        
        // 更新详情
        item.querySelector('.sync-history-details').textContent = record.details || '';
      }
    });
    
    // 隐藏多余的历史记录项
    for (let i = recentHistory.length; i < historyItems.length; i++) {
      historyItems[i].style.display = 'none';
    }
  }
}

// Format date for display
function formatDate(dateString) {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 修改现有的syncWithJsonBin函数，添加同步历史记录
async function syncWithJsonBin() {
  const apiKey = localStorage.getItem('jsonBinApiKey');
  const binId = localStorage.getItem('jsonBinBinId');
  if (!apiKey || !binId) {
    showNotification('Please configure JSONBin settings first', 'error');
    return;
  }
  // 优先从 chrome.storage.local 读取
  let tasksData = [];
  if (window.chrome && chrome.storage && chrome.storage.local) {
    tasksData = await new Promise(resolve => {
      chrome.storage.local.get(['taskTrackerTasks'], function(result) {
        resolve(result.taskTrackerTasks || []);
      });
    });
  } else {
    tasksData = JSON.parse(localStorage.getItem('taskTrackerTasks') || '[]');
  }
  // 创建新的同步记录
  const syncRecord = {
    date: new Date().toISOString(),
    success: false,
    details: ''
  };
  try {
    const response = await fetch(`https://api.jsonbin.io/v3/b/${binId}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'X-Master-Key': apiKey
      },
      body: JSON.stringify(tasksData)
    });
    if (!response.ok) {
      throw new Error(`Status: ${response.status}`);
    }
    const data = await response.json();
    syncRecord.success = true;
    syncRecord.details = `Uploaded ${tasksData.length} items`;
    showNotification('Data synchronized with JSONBin successfully');
    localStorage.setItem('lastSyncTime', Date.now().toString());
    // 下载云端数据并同步到 chrome.storage.local
    if (window.chrome && chrome.storage && chrome.storage.local) {
      // 读取云端最新数据
      const getResp = await fetch(`https://api.jsonbin.io/v3/b/${binId}/latest`, {
        method: 'GET',
        headers: { 'X-Master-Key': apiKey }
      });
      if (getResp.ok) {
        const json = await getResp.json();
        if (json && json.record) {
          chrome.storage.local.set({ taskTrackerTasks: json.record });
          localStorage.setItem('taskTrackerTasks', JSON.stringify(json.record));
        }
      }
    }
  } catch (error) {
    syncRecord.success = false;
    syncRecord.details = `Error: ${error.message}`;
    showNotification(`Sync failed: ${error.message}`, 'error');
  } finally {
    saveSyncHistory(syncRecord);
  }
}

// 保存同步历史记录
function saveSyncHistory(syncRecord) {
  // 获取现有历史记录
  let syncHistory = JSON.parse(localStorage.getItem('syncHistory') || '[]');
  
  // 添加新记录到开头
  syncHistory.unshift(syncRecord);
  
  // 限制最多保存10条记录
  if (syncHistory.length > 10) {
    syncHistory = syncHistory.slice(0, 10);
  }
  
  // 保存到localStorage
  localStorage.setItem('syncHistory', JSON.stringify(syncHistory));
}

// Initialize auto sync based on stored settings
function initializeAutoSync() {
  const cloudSyncEnabled = localStorage.getItem('cloudSyncEnabled') === 'true';
  
  if (cloudSyncEnabled) {
    resetAutoSyncTimer();
  }
}

// Reset and start auto sync timer based on selected frequency
function resetAutoSyncTimer() {
  // Clear existing timer if any
  if (syncTimer) {
    clearInterval(syncTimer);
    syncTimer = null;
  }
  const cloudSyncEnabled = localStorage.getItem('cloudSyncEnabled') === 'true';
  if (!cloudSyncEnabled) {
    return; // Don't set timer if sync is disabled
  }
  const frequency = localStorage.getItem('syncFrequency') || '1hour';
  let intervalMs = 0;
  switch (frequency) {
    case '1min':
      intervalMs = 1 * 60 * 1000;
      break;
    case '1hour':
      intervalMs = 60 * 60 * 1000;
      break;
    case '3hour':
      intervalMs = 3 * 60 * 60 * 1000;
      break;
    case '9hour':
      intervalMs = 9 * 60 * 60 * 1000;
      break;
    default:
      return;
  }
  // 读取上次同步时间
  const lastSyncTime = parseInt(localStorage.getItem('lastSyncTime') || '0', 10);
  const now = Date.now();
  const timeSinceLastSync = now - lastSyncTime;
  if (!lastSyncTime || timeSinceLastSync >= intervalMs) {
    // 没有同步过或已超时，立即同步
    syncWithJsonBin();
    // 下次定时 intervalMs 后再同步
    syncTimer = setInterval(() => {
      syncWithJsonBin();
    }, intervalMs);
  } else {
    // 还没到时间，等剩余时间后同步
    const remaining = intervalMs - timeSinceLastSync;
    syncTimer = setTimeout(function doSync() {
      syncWithJsonBin();
      // 之后每隔 intervalMs 再同步
      syncTimer = setInterval(() => {
        syncWithJsonBin();
      }, intervalMs);
    }, remaining);
  }
} 